import React, { createContext, useContext, useReducer, useEffect } from "react";
import { USER_TYPES } from "../utils/userUtils";
import { getUserInfoApi } from "../api/user";
import Cookies from "js-cookie";

// 安全解析 localStorage
const safeParse = (key) => {
  try {
    const item = localStorage.getItem(key);
    return item ? JSON.parse(item) : null;
  } catch {
    return null;
  }
};

// 初始状态
const initialState = {
  userType: safeParse("users")?.userType || null,
  userInfo: safeParse("users")?.userInfo || null,
  loadingUserInfo: false,
};

// Reducer 函数
function reducer(state, action) {
  let newState;
  switch (action.type) {
    case "SET_USER_TYPE":
      newState = {
        ...state,
        userType: Object.values(USER_TYPES).includes(action.payload)
          ? action.payload
          : null,
      };
      break;
    case "SET_USER_INFO":
      newState = {
        ...state,
        userInfo: action.payload,
        userType: action.payload?.role || state.userType,
      };
      break;
    case "SET_LOADING_USER_INFO":
      newState = { ...state, loadingUserInfo: action.payload };
      break;
    case "CLEAR_USER_INFO":
      // 清除所有用户相关信息
      Cookies.remove("access_token");
      localStorage.removeItem("users");
      localStorage.removeItem(`chat_history_${state.userInfo?.id}`);
      newState = {
        userType: null,
        userInfo: null,
        loadingUserInfo: false,
      };
      break;
    default:
      newState = state;
  }

  // 只在有用户信息时才持久化数据
  if (newState.userInfo) {
    localStorage.setItem(
      "users",
      JSON.stringify({
        userType: newState.userType,
        userInfo: newState.userInfo,
      })
    );
  }

  return newState;
}

// 创建 Context
const StoreContext = createContext();

// Store Provider 组件
export function StoreProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  // 获取用户信息方法
  const getUserInfo = async (force = false) => {
    if (state.loadingUserInfo) return;

    const hasToken = !!Cookies.get("access_token");
    const shouldFetch = force || (hasToken && !state.userInfo);

    if (!shouldFetch) return;

    dispatch({ type: "SET_LOADING_USER_INFO", payload: true });

    try {
      const userInfo = await getUserInfoApi();
      if (!userInfo?.id) throw new Error("Invalid user data");

      dispatch({ type: "SET_USER_INFO", payload: userInfo });
    } catch (error) {
      console.error("获取用户信息失败:", error);
      if (error.response?.status === 401) {
        Cookies.remove("access_token");
        dispatch({ type: "LOGOUT" });
      }
    } finally {
      dispatch({ type: "SET_LOADING_USER_INFO", payload: false });
    }
  };

  return (
    <StoreContext.Provider value={{ state, dispatch, getUserInfo }}>
      {children}
    </StoreContext.Provider>
  );
}

// 自定义 Hook
export function useStore() {
  const context = useContext(StoreContext);
  if (!context) {
    throw new Error("useStore must be used within a StoreProvider");
  }
  return context;
}
